from django.shortcuts import render

# Create your views here.
from utils.response import APIResponse
from .models import Order
from .serializer import OrderSerializer
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import CreateModelMixin

from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated
class OrderView(GenericViewSet, CreateModelMixin):
    # 登陆后才能访问
    authentication_classes = [JSONWebTokenAuthentication,]
    permission_classes = [IsAuthenticated]
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data,context={'request':request})
        serializer.is_valid(raise_exception=True)
        pay_url = serializer.context.get('pay_url')
        self.perform_create(serializer)
        return APIResponse(pay_url=pay_url)


from utils.log import logger
# from rest_framework.viewsets import ViewSet
from rest_framework.views import  APIView
from rest_framework.response import Response
# 支付回调接口
class SuccessViewSet(APIView):
    # 认证取消
    authentication_classes = ()
    permission_classes = ()
    # 支付宝同步回调给前台，在同步通知给后台处理
    # 写不写都行---》给咱们前端做二次验证的
    def get(self, request, *args, **kwargs):
        # return Response('后台已知晓，Over！！！')
        # 不能在该接口完成订单修改操作
        # 但是可以在该接口中校验订单状态(已经收到支付宝post异步通知，订单已修改)，告诉前台
        # print(type(request.query_params))  # django.http.request.QueryDict
        # print(type(request.query_params.dict()))  # dict

        out_trade_no = request.query_params.get('out_trade_no')
        try:
            Order.objects.get(out_trade_no=out_trade_no, order_status=1)
            return APIResponse(status=100,msg='订单支付成功')
        except:
            return APIResponse(status=101,msg='订单还未支付')


    # 支付宝异步回调处理
    def post(self, request, *args, **kwargs):
        try:
            # request.data前端(支付宝)post传给咱们的数据--》request.data--》 QueyDic对象，不允许pop，把它转成字典
            result_data = request.data.dict()
            # 支付宝给我的订单号---》数据库有个订单号
            out_trade_no = result_data.get('out_trade_no')
            # 前面-->验证签名才信任支付宝，防止伪造
            signature = result_data.pop('sign')
            from libs import iPay
            result = iPay.alipay.verify(result_data, signature)
            if result and result_data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
                # 完成订单修改：订单状态、流水号、支付时间
                # 已支付
                Order.objects.filter(out_trade_no=out_trade_no).update(order_status=1)
                # 完成日志记录
                logger.warning('%s订单支付成功' % out_trade_no)
                return Response('success')
            else:
                logger.error('%s订单支付失败' % out_trade_no)
        except:
            pass
        return Response('failed')